//
//  GLHTTPTool.m
//  SXBPurchase
//
//  Created by huanggulong on 2017/10/8.
//  Copyright © 2017年 历山大亚. All rights reserved.
//

#import "GLHTTPTool.h"
#import <AFNetworking/AFNetworking.h>
#import "GLDevice.h"

extern NSString * Access_token;

@implementation GLHTTPTool

+ (AFSecurityPolicy *)customSecurityPolicy{
    
    NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"GLHTTPS" ofType:@"cer"];
    NSData *cerData = [NSData dataWithContentsOfFile:cerPath];
    AFSecurityPolicy *security = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
    if (cerData) {
        security.allowInvalidCertificates = YES;
        security.validatesDomainName = NO;
        security.pinnedCertificates = [NSSet setWithObject:cerData];
    }
    return security;
}

+ (AFHTTPSessionManager *)sharedManager
{
    static AFHTTPSessionManager *manager = nil;
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        manager = [AFHTTPSessionManager manager];
        manager.operationQueue.maxConcurrentOperationCount = 5;
        manager.requestSerializer.timeoutInterval=30.f;
        
        [manager.requestSerializer setValue:[[GLDevice device] platformString] forHTTPHeaderField:@"phoneModel"];
        [manager.requestSerializer setValue:[[GLDevice device] systemVersion] forHTTPHeaderField:@"sversion"];
        [manager.requestSerializer setValue:[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"] forHTTPHeaderField:@"appVersion"];
        manager.responseSerializer.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"application/xml", @"text/xml",@"text/html", @"application/json",@"text/plain",nil];
        [manager.requestSerializer setValue:@"gzip" forHTTPHeaderField:@"Content-Encoding"];
    });
    return manager;
}

+(NSURLSessionDataTask *)postWithURL:(NSString *)url params:(NSDictionary *)params success:(void (^)(id))success failure:(void (^)(NSError *))failure{
    if (![url hasPrefix:@"http://"] && ![url hasPrefix:@"https://"]) {
        if (failure) {
            NSError *error = [NSError errorWithDomain:@"org.gulong" code:1024 userInfo:@{NSLocalizedDescriptionKey:@"非http请求"}];
            failure(error);
        }
        return nil; //不做任何的保护 到达底层了还有问题就抛出去自己解决了再来请求
    }
    
    NSString *logURLString = [NSString stringWithFormat:@"%@?", url];
    
    for (NSString *key in params.allKeys) {
        id value = [params objectForKey:key];
        if ([value isKindOfClass:[NSNull class]]) {
            value = @" ";
        }
        logURLString = [logURLString stringByAppendingFormat:@"%@=%@&", key, value];
    }
    NSLog(@"网络请求 :%@",logURLString);
    AFHTTPSessionManager *manager = [self sharedManager];
    manager.securityPolicy = [self customSecurityPolicy];
    if (Access_token) {
        NSString * Access2 = [NSString stringWithFormat:@"bearer %@",Access_token];
        [manager.requestSerializer setValue:Access2 forHTTPHeaderField:@"Authorization"];
        [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    }
    NSURLSessionDataTask *sessionTask = [manager POST:url parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"数据%@成功:%@",task.currentRequest.URL.absoluteString, responseObject);
        if (success) {/*  若成功，返回数据  */
            success(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {/*  若失败，返回错误信息  */
            failure(error);
        }
        
        NSLog(@"数据%@失败:%@",[task.currentRequest.URL absoluteString], error);
    }];
    [sessionTask resume];
    return sessionTask;
}

+(NSURLSessionDataTask *)jsonWithURL:(NSString *)url params:(NSDictionary *)params success:(void (^)(id))success failure:(void (^)(NSError *))failure{
    if (![url hasPrefix:@"http://"] && ![url hasPrefix:@"https://"]) {
        if (failure) {
            NSError *error = [NSError errorWithDomain:@"org.gulong" code:1024 userInfo:@{NSLocalizedDescriptionKey:@"非http请求"}];
            failure(error);
        }
        return nil; //不做任何的保护 到达底层了还有问题就抛出去自己解决了再来请求
    }
    
    NSString *logURLString = [NSString stringWithFormat:@"%@?", url];
    
    for (NSString *key in params.allKeys) {
        id value = [params objectForKey:key];
        if ([value isKindOfClass:[NSNull class]]) {
            value = @" ";
        }
        logURLString = [logURLString stringByAppendingFormat:@"%@=%@&", key, value];
    }
    NSLog(@"网络请求 :%@",logURLString);
    AFHTTPSessionManager *manager = [self sharedManager];
    manager.securityPolicy = [self customSecurityPolicy];
    
    NSMutableURLRequest * request = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:url parameters:nil error:NULL];
    
    if (Access_token) {
        NSString * Access2 = [NSString stringWithFormat:@"bearer %@",Access_token];
        [request setValue:Access2 forHTTPHeaderField:@"Authorization"];
        [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    }
    [request setValue:[[GLDevice device] platformString] forHTTPHeaderField:@"phoneModel"];
    [request setValue:[[GLDevice device] systemVersion] forHTTPHeaderField:@"sversion"];
    [request setValue:@"gzip" forHTTPHeaderField:@"Content-Encoding"];
    [request setValue:[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"] forHTTPHeaderField:@"appVersion"];
    if (params) {
        NSData * data = [NSJSONSerialization dataWithJSONObject:params options:0 error:NULL];
        [request setHTTPBody:data];
    }
    NSURLSessionDataTask *sessionTask = [manager dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        if (error) {
            if (failure) {/*  若失败，返回错误信息  */
                failure(error);
            }
            NSLog(@"数据%@失败:%@",[response.URL absoluteString], error);
        }else{
            NSLog(@"数据%@成功:%@",response.URL.absoluteString, responseObject);
            if (success) {/*  若成功，返回数据  */
                success(responseObject);
            }
        }
    }];
    [sessionTask resume];
    return sessionTask;
}

+ (NSURLSessionDataTask *)getWithURL:(NSString *)url params:(NSDictionary *)params success:(void (^)(id))success failure:(void (^)(NSError *))failure {
    if (![url hasPrefix:@"http://"] && ![url hasPrefix:@"https://"]) {
        if (failure) {
            NSError *error = [NSError errorWithDomain:@"org.gulong" code:1024 userInfo:@{NSLocalizedDescriptionKey:@"非http请求"}];
            failure(error);
        }
        return nil; //不做任何的保护 到达底层了还有问题就抛出去自己解决了再来请求
    }
    AFHTTPSessionManager *manager = [self sharedManager];
    manager.securityPolicy = [self customSecurityPolicy];
    NSString * Access2 = [NSString stringWithFormat:@"bearer %@",Access_token];
    [manager.requestSerializer setValue:Access2 forHTTPHeaderField:@"Authorization"];
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    NSURLSessionDataTask *sessionTask = [manager GET:url parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success) {/*  若成功，返回数据  */
            success(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {/*  若失败，返回错误信息  */
            failure(error);
        }
    }];
    [sessionTask resume];
    return sessionTask;
}

+(void)uploadPostWithURL:(NSString *)url fileUrl:(NSData *)fileData andParam:(NSDictionary *)params  completion:(void (^)(id json))complete progress:(NSProgress *)progress failure:(void (^)(NSError *))failure{
    
    
    AFHTTPSessionManager *manager = [self sharedManager];
    manager.securityPolicy = [self customSecurityPolicy];
    NSError *error = nil;
    NSData *data = fileData;
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:url parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFileData:data name:@"file" fileName:@"123.png" mimeType:@"image/png"];
        //        [formData appendPartWithFormData:data name:@"FileData"];
    } error:&error];
    if (error) {
        if (failure) {
            failure(error);
        }
        return;
    }
    [request setValue:[@"Bearer " stringByAppendingString:gl_loginToken] forHTTPHeaderField:@"Authorization"];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];
    
    
    [[manager uploadTaskWithStreamedRequest:request progress:^(NSProgress * _Nonnull uploadProgress) {
        if (progress != NULL) {
            //            (*progress).completedUnitCount = uploadProgress.completedUnitCount;
            //            (*progress).totalUnitCount = uploadProgress.totalUnitCount;
        }
        NSLog(@"%lld -- %lld",uploadProgress.completedUnitCount,uploadProgress.totalUnitCount);
    } completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        if (error) {
            if (failure) {
                failure(error);
            }
        }else{
            if (complete) {
                complete(responseObject);
            }
        }
    }] resume];
    
}

static NSString * gl_loginToken = nil;
+(void)setLoginToken:(NSString *)loginToken {
    if (loginToken.length == 0) {
        [[self sharedManager].requestSerializer setValue:@"" forHTTPHeaderField:@"Authorization"];
        gl_loginToken = @"";
    }else{
        [[self sharedManager].requestSerializer setValue:[@"Bearer " stringByAppendingString:loginToken] forHTTPHeaderField:@"Authorization"];
        gl_loginToken = loginToken;
    }
    NSLog(@"%@",[[self sharedManager].requestSerializer HTTPRequestHeaders]);
}

@end
